<template>
  <div class="login">
    <div class="login-btn" v-if="!qrImg">
      <button  @click="onLogin">登录</button>
      <div class="tip">当前仅支持扫码登录</div>
    </div>
  <div class="login-btn" v-if="qrImg" >
    <img :src="qrImg" alt="" v-if="!isTrue">
    <div v-else>二维码失效</div>
    <div  class="tip" @click="onLogin">点击刷新二维码</div>
  </div>

  </div>
</template>
<script setup>
import {onMounted, reactive, ref} from "vue";
import {useRoute} from 'vue-router'

const route = useRoute()
import {loginQrCreate, loginStatus, loginQrKey, checkStatus} from "../../api/login/index.ts";
let isTrue = ref(false)
let qrImg = ref('')
let form = reactive({})
const onLogin = () => {
  let timer = null
  const key = ref('')
  const cookie = localStorage.getItem('cookie')
  getLoginStatus(cookie)
  loginQrKey().then(re => {
    key.value = re.data.unikey
    loginQrCreate(key.value).then(r => {
      qrImg.value = r.data.qrimg
    })
  })
  timer = setInterval( () => {
   getCheckStatus(key.value,timer)
  }, 30000)
}
const getLoginStatus = (cookie) => {
  loginStatus(cookie).then(res => {
    console.log(res)
  })
}
const getCheckStatus = (key,timer) => {
  checkStatus(key).then(res => {
    console.log(res)
    const statusRes = res
    if (statusRes.code === 800) {
isTrue.value = true
      console.log('二维码已过期,请重新获取')
      clearInterval(timer)
    }
    if (statusRes.code === 803) {
      // 这一步会返回cookie
      clearInterval(timer)
      console.log('扫码登录成功')
      getLoginStatus(statusRes.cookie)
      localStorage.setItem('cookie', statusRes.cookie)
    }
  })
}

onMounted(() => {

})
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  position: relative;
  //background-color: #dd001b;
  .login-btn {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    text-align: center;
    button {
      color: #ffffff;
      width: 120px;
      height: 40px;
      line-height: 40px;
      border: none;
      outline: none;
      cursor: pointer;
      background-color: #ec4141;
      border-radius: 4px;
    }
    button:active {
      background-color: #ec4141;
      color: #fff;
    }
    .tip {
      font-size: 12px;
      color: #eeeeef;
    }
  }

}
</style>